package pers.lxl.structure.queue;

/**
 * 自定义的循环队列
 *
 * @date & @author: 2018/12/16 18:57 & lxl
 */
public class LoopQueue<E> implements Queue<E> {

    /**
     * 存放数据的数组
     */
    private E[] data;

    /**
     * 队列头指针(索引)
     */
    private int front;

    /**
     * 队列尾指针(索引)
     */
    private int tail;

    /**
     * 存放数据的数量
     */
    private int size;

    public LoopQueue() {
        this(10);
    }

    public LoopQueue(int capacity) {
        // 因为要冗余一个空数据, 所以创建的时候在数组中多创建一个空位置
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    public int getCapacity() {
        // 因为创建的时候冗余了一个长度, 所以这里要减去一个
        return data.length - 1;
    }

    /**
     * 查看队列是否为空 front == tail时为空
     *
     * @return true = 为空, false = 不为空
     */
    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public void enqueue(E e) {
        // 队列满时((tail + 1)/data.length == front , 为了和队列空时区分, 所以冗余了一个元素), 调用扩容方法
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }

        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    @Override
    public E dequeue() {

        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue!");
        }

        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;

        if (size == getCapacity() / 4 && (getCapacity() / 2) != 0) {
            resize(getCapacity() / 2);
        }

        return ret;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue!");
        }
        return data[front];
    }

    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }

        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(String.format("LoopQueue: size = %d, capacity = %d\n", size, getCapacity()))
                .append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            builder.append(data[i]);
            if ((i + 1) % data.length != tail) {
                builder.append(", ");
            }

        }
        builder.append("] tail");
        return builder.toString();
    }
}
